<?php

namespace Parser\Separator;

use Parser\Enquiry;
use Parser\Parser;
use Parser\Repetition;

class TAISHAN implements BaseSeparator
{
    public static $ApiKindList = [
        3000 => '030006', //车损
        4000 => '030018', //三者
        5002 => '030001', //司机
        5001 => '030009', //乘客
    ];

    private $errorTip;

    public function interpreter(array $array, $parser)
    {
        if ($this->error($array, $parser)) {
            return;
        }

        $parser->result = $this->analysis($array);
    }

    /**
     *错误解析
     * Author:ls
     *
     * @param $array
     * @param Parser $parser
     * @return bool
     */
    public function error(&$array, $parser): bool
    {
        if ($message = $array['message'] ?? '' and $message != 'OK') {
            $parser->message = $message ?? "系统异常";
            $parser->code = '500';
            return true;
        }

        $TCIFlag = $array['result']['compulsoryInsurance']['productInfo']['insureItemFlag'] ?? '';
        $VCIFlag = $array['result']['businessInsurance']['productInfo']['insureItemFlag'] ?? '';

        if ($remark = $array['result']['proposalInfo']['reMark'] ?? '') {
            if ($TCIFlag and $remark) {
                $parser->message = $remark;
                $parser->code = '500';
                return true;
            }
            if ($VCIFlag and $remark) {
                $this->errorTip = $remark;
            }
        }
        if ($exception = $array['result']['exception']['msg'] ?? '') {
            if ($exception != '接口调用成功') {
                $parser->message = $exception;
                $parser->code = '500';
                return true;
            }
        }

        if (!$array = $array['result']) {
            $parser->message = "系统异常";
            $parser->code = '500';
            return true;
        }

        return false;
    }


    public function analysis($array): array
    {
        $enquiry = new Enquiry();

        //交强险

        $enquiry->setTaxTotal($array['compulsoryInsurance']['carShipTax']['unitTaxAmt'] ?? '0');
        $enquiry->setTaxPremium($array['compulsoryInsurance']['carShipTax']['sumTax'] ?? '0');
        $enquiry->setTCITotal($array['compulsoryInsurance']['productInfo']['premium'] ?? '0');
        //折扣
        $enquiry->setVCIDiscount($array['proposalInfo']['syAdjustRate'] ?? '');

        //商业险
        if ($businessInsurance = $array['businessInsurance']['itemKinds'] ?? []) {
            foreach ($businessInsurance as $value) {
                $coverages['code'] = (string)array_search($value['kindCode'], self::$ApiKindList);
                $coverages['shortName'] = (string)$value['kindName'] ?? '';
                $coverages['insuredDesc'] = (string)$value['amount'] ?? '';
                $coverages['total'] = (string)$value['premium'] ?? '';

                $enquiry->setVCICoverages($coverages);
                $enquiry->VCITotalAppend($value['premium']);
                $enquiry->VCIPremiumAppend($value['basePrm']);

            }
        }

        //交强险
        if ($compulsoryInsurance = $array['compulsoryInsurance']['itemKinds'] ?? []) {
            foreach ($compulsoryInsurance as $value) {
                $enquiry->TCIPremiumAppend($value['basePrm']);
            }
        }
        //商业险费率因子
        if ($coefficientInfo = $array['coefficientInfo'] ?? []) {
            //自主定价
            $enquiry->setIndependentPriceRatio($coefficientInfo['resvNumAutonomy'] ?? '');
            //无赔款优待系数
            $enquiry->setNCDRate($coefficientInfo['syAgoClmRecCoeff'] ?? '0');
        }

        $enquiry->setTotal();

        if ($this->errorTip) {
            $enquiry->failure();
            $enquiry->setErrorTip('商业险重复投保');
        }

        $enquiry->success();

        return $enquiry->get();
    }

    //数据解析
    public function repetition($array): Repetition
    {
        $repetition = new Repetition();

        if ($repeatMsg = $array['result']['proposalInfo']['reMark'] ?? false) {

            if (mb_strlen($repeatMsg) < 400) {
                return $repetition;
            }

            $repeatMsg = explode("\n", trim($repeatMsg, "\n"));
            str_replace('：', '：', $repeatMsg);
            $tmp = [];
            foreach ($repeatMsg as $value) {
                $value = trim($value, ';');
                $value = explode('：', $value);

                if (($value[1] ?? '') and !key_exists($value[0], $tmp)) {
                    $tmp[$value[0]] = trim($value[1]);
                }
            }

            foreach ($tmp as $key => $value) {
                switch ($key) {
                    case '重复投保保单号':
                        $repetition->setLastPolicy($value);
                        break;
                    case '保险公司代码':
                        $repetition->setLastCompany($value);
                        break;
                    case '号牌号码':
                        $repetition->setLicense($value);
                        break;
                    case '起保日期':
                        $begin = strtotime($value);
                        if ($begin) {
                            $repetition->setLastStartAt(date('Y-m-d H:i:s', $begin));
                        }
                        break;
                    case '终保日期':
                        $endAt = strtotime($value);
                        if ($endAt) {
                            $repetition->setLastEndTime(date('Y-m-d H:i:s', $endAt));
                        }
                        break;
                    case '险种名称':
                        $coverage = explode('、', $value);
                        $repetition->setLastCoverage($coverage);
                        break;
                }
            }

            if ($repetition->getLastCompany()) {
                $repetition->setStatus('success');
            }
        }
        return $repetition;
    }
}

